/**
 * @description 设置cookie
 * @param key
 * @param value - cookie值
 * @param expires
 */
function setCookie(key, value, expires = 2 * 365 * 24 * 60 * 60 * 1000) {
  const date = new Date()
  date.setTime(date.getTime() + expires)
  const expiresString = date.toUTCString()
  document.cookie = `${key}=${value};expires=${expiresString};path=/`
}

function getCookie(key) {
  const name = `${key}=`
  const decodedCookie = decodeURIComponent(document.cookie)
  const ca = decodedCookie.split(';')
  for (let i = 0; i < ca.length; i++) {
    let c = ca[i]
    while (c.charAt(0) === ' ') {
      c = c.substring(1)
    }
    if (c.indexOf(name) === 0) {
      return c.substring(name.length, c.length)
    }
  }
  return undefined
}

function deleteCookie(name) {
  setCookie(name, '', -1)
}

function getAllCookies() {
  const cookies = {}
  const decodedCookie = decodeURIComponent(document.cookie)
  const ca = decodedCookie.split(';')
  for (let i = 0; i < ca.length; i++) {
    const cookie = ca[i]
    const [key, value] = cookie.split('=').map(c => c.trim())
    cookies[key] = value
  }
  return cookies
}

function clearAllCookies() {
  const cookies = document.cookie.split(';')
  for (let i = 0; i < cookies.length; i++) {
    const cookie = cookies[i]
    const eqPos = cookie.indexOf('=')
    const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie
    document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`
  }
}

export const cookies = {
  set: setCookie,
  get: getCookie,
  delete: deleteCookie,
  getAll: getAllCookies,
  clearAll: clearAllCookies,
}
